#include<stdio.h>
#include <string.h>
#include <stdlib.h>
#include <math.h>

char *currentLine = NULL;
char *pointer = NULL;
int seek = 0;
int line = 1; 

void saveToEditor(char *line)
{
  
}

void readLine(FILE *fp)
{
  char c;
  int lineLength = 0;
  int currentLineSize = 128;
  currentLine = (char *)malloc(currentLineSize*sizeof(char));
  memset(currentLine,0,currentLineSize*sizeof(char));
  
  if(fp == NULL) 
    {
      printf("open input source file fail");
      exit(1);
    }
  
  while ((c = fgetc(fp)) != EOF)
    {
      if(c == '\n')
        break;
      
      if(lineLength >= currentLineSize)
        {
          currentLine = (char*)realloc(currentLine,2*currentLineSize*sizeof(char));
        }
      currentLine[lineLength++] = c;      
    }

  if(c == EOF) 
    {
      line = 0;
      if(currentLine != NULL)
        free(currentLine);
      if(pointer != NULL)
        free(pointer);
      currentLine = NULL;
      pointer = NULL;  
      return;
    }
  pointer = currentLine;
  saveToEditor(currentLine);
}

char GetNextChar(FILE *fp)
{
  char *s;
  char returnValue;

  if(line == 0)
    return EOF;
  
  if(currentLine == NULL)  
    {
      readLine(fp);
    }
  
  s = pointer;
  // Do something here to skip the '\n' '\t'

  for(;;)
    {
      switch(*s)
        {
        case '\n':
          readLine(fp);
          s = pointer;
          return '\n';

        case ' ':
        case '\t':
        case '\f':
        case '\r':
        case '\v':
          returnValue = *s; 
          ++s;
          return returnValue;

        case ';':
          // skip to the end of line
          while((*s) != '\n')
            ++s;
          readLine(fp);
          /*
            if ';' is at the end of files
           */
          if(line != 0)
            s = pointer;
          else
            return EOF;
          break;

        default:
          pointer = s;
          returnValue = *s;
          s++;
          return returnValue;
        }
    }
}
